<?php


namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_express_type\Entity\ShusyExpressType;
use Drupal\shusy_store_order\Entity\ShusyStoreOrder;
use Drupal\shusy_store_order_express\Entity\ShusyStoreOrderExpress;

/**
 * @OA\Schema(
 *   schema="OrderLogistics",
 *   type="object",
 *   description="OrderLogistics",
 *   allOf={
 *       @OA\Schema(ref="#/components/schemas/OrderPayment"),
 *   }
 * )
 */
class OrderLogistics extends OrderPayment {

  protected function setValue() {
    parent::setValue();
    if ($this->entity instanceof ShusyStoreOrder) {
      $express = $this->getExpress($this->entity);
      //顺丰需要后四位
      $phone = '';
      if (isset($this->value['address'])) {
        $phone = $this->value['address']->telNumber;
      }
      $value = [
        /**
         * @OA\Property(
         *   property="logistics",
         *   type="array",
         *   description="物流记录",
         *   @OA\Items(type="object",
         *     @OA\Property(property="time",type="string",description="时间"),
         *     @OA\Property(property="content",type="string",description="内容"),
         *   )
         * ),
         */
        'logistics' => $this->getLogistics($express, $phone),
        /**
         * @OA\Property(
         *   property="logisticsCompany",
         *   type="string",
         *   description="物流公司",
         * ),
         */
        'logisticsCompany' => (string) $express['logisticsCompany'],
        /**
         * @OA\Property(
         *   property="logisticsNumber",
         *   type="string",
         *   description="物流单号",
         * ),
         */
        'logisticsNumber' => (string) $express['logisticsNumber'],
      ];
      $this->merge($value);
    }
  }

  /**
   * @param $express
   * [
   * ['time' => '2020-04-13 12:00', 'content' => '入 成都双流中转仓'],
   * ]
   *
   * @return array
   */
  protected function getLogistics($express, $phone = "") {
    $logisticsNumber = $express['logisticsNumber'];
    $type = $express['type'];
    $list = [];
    if ($type == 'SFEXPRESS') {
      $logisticsNumber .= ':' . mb_substr($phone, -4);
    }
    $host = "https://wuliu.market.alicloudapi.com";//api访问链接
    $path = "/kdi";//API访问后缀
    $method = "GET";
    $appcode = "edc81f737dca4f56b99f0be0a2b3a644";//开通服务后 买家中心-查看AppCode
    $headers = [];
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "no={$logisticsNumber}&type={$type}";  //参数写在这里
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_HEADER, TRUE);
    if (1 == strpos("$" . $host, "https://")) {
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    $out_put = curl_exec($curl);

    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    [$header, $body] = explode("\r\n\r\n", $out_put, 2);
    if ($httpCode == 200) {
      $result = drupal_json_decode($body);
      watchdog(__FUNCTION__, serialize($result));
      if ($result['status'] == 0) {
        $tmps = $result['result']['list'];
        foreach ($tmps as $item) {
          $list[] = [
            'time' => $item['time'],
            'content' => $item['status'],
          ];
        }
      }
    }
    return $list;
  }

  protected function getExpress(ShusyStoreOrder $order) {
    //shusy_store_order_express
    $es = shusy_store_order_express_load_multiple(FALSE, [
      'store_order_id' => $order->id,
    ]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyStoreOrderExpress) {
        $type = shusy_express_type_load($e->express_type_id);
        if ($type instanceof ShusyExpressType) {
          return [
            'logisticsCompany' => $type->express_name,
            'logisticsNumber' => $e->express_number,
            'type' => $type->express_code,
          ];
        }
      }
    }
    return [
      'logisticsCompany' => '',
      'logisticsNumber' => '',
      'type' => '',
    ];
  }
}
